#! /bin/python

################################################################################
#	\file   SConscript
#	\author Gregory Diamos <solusstuluts@gmail.com>
#   \date   Tuesday March 5, 2013
#	\brief  The SCons master build script for the NV libc implementation.
################################################################################

import os

# set environment variables
Import('nvenv')

env = nvenv

# Helper functions
def getSubdirectories(path):
	directories = set([path])
	
	for root, dirs, files in os.walk(path):
		for dir in dirs:
			if dir != None:
				directories.add(os.path.join(root, dir))

	return directories

def findLibraryPath():
	return os.path.realpath(os.path.join(env['path_to_root_dir'],
		'libc', 'include'))

def findSuffix(basePath, completePath):
	head, tail = os.path.split(os.path.realpath(completePath))

	suffix = ''

	while len(tail) > 0:
		if os.path.samefile(head, basePath):
			return suffix
		
		head, tail = os.path.split(head)
		suffix = os.path.join(tail, suffix)
	
	return None

# find the path
libraryPath = findLibraryPath()

# set up the include path
env.AppendUnique(CPPPATH = ['interface'])

if env['install']:
	directories = ['libc']

	source_directories = directories
	extensions = ['*.cpp', '*.c']

	sources = []
	for dir in source_directories:
		for ext in extensions:
			regexp = os.path.join(dir, ext)
			sources.extend(env.Glob(regexp))
	
	# create the library
	libc = env.SharedLibrary('libc', sources)
	libc_libs = ['libc'] + env['EXTRA_LIBS']
	
	libc = env.Install(os.path.join(env['install_path'], "lib"),
		libc)

	env.Depends(libc, os.path.join(env['install_path'], "include"))

	# create the tests
	tests = []

	#tests.append(env.Program('gpu-native-loader', \
	#	['gpu-native/tools/gpu-native-loader.cpp'], LIBS=gpunative_libs))

	for test in tests:
		env.Depends(test, libc)

# install it all 
if env['install']:
	installed   = []
	executables = []

	print 'Installing libc from ' + libraryPath 
	
	# install headers 
	header_directories = [i for i in getSubdirectories(libraryPath)]
	header_extensions = ['*.h']

	headers = []
	for dir in header_directories:
		for ext in header_extensions:
			regexp = os.path.join(dir, ext)
			headers.extend(env.Glob(regexp))

	for header in headers:
		headerName = findSuffix(libraryPath, str(header))
		
		installPath = os.path.join(env['install_path'], "include", "libc", headerName)
		
		installed.append(env.Install(installPath, header))
		
	# set permissions
	for i in executables:
		env.AddPostAction(i, Chmod(i, 0755))
	for i in installed:
		env.AddPostAction(i, Chmod(i, 0644))


